package com.ybxx.fees.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.ybxx.base.model.Residents;
import com.ybxx.base.model.Room;
import com.ybxx.base.model.RoomInfo;
import com.ybxx.base.service.CommunityService;
import com.ybxx.base.service.HydropowerItemService;
import com.ybxx.base.service.ResidentsService;
import com.ybxx.base.service.RoomInfoService;
import com.ybxx.base.service.RoomService;
import com.ybxx.core.command.QueryFilter;
import com.ybxx.core.util.DateUtil;
import com.ybxx.core.util.UUIDGenerator;
import com.ybxx.core.web.action.BaseAction;
import com.ybxx.fees.model.AnmeterRecordItem;
import com.ybxx.fees.model.AnmeterRecords;
import com.ybxx.fees.model.FfRecord;
import com.ybxx.fees.model.GlfRecord;
import com.ybxx.fees.model.HlfRecord;
import com.ybxx.fees.model.OtherRecordItem;
import com.ybxx.fees.model.Records;
import com.ybxx.fees.model.RecordsVO;
import com.ybxx.fees.model.WatermeterRecordItem;
import com.ybxx.fees.model.WatermeterRecords;
import com.ybxx.fees.model.WsfRecord;
import com.ybxx.fees.model.WsfRecordItem;
import com.ybxx.fees.service.AnmeterRecordsService;
import com.ybxx.fees.service.RecordsService;
import com.ybxx.fees.service.WatermeterRecordsService;
import com.ybxx.fees.service.WsfRecordService;
import com.ybxx.fees.uti.ConvertRecord;
import com.ybxx.system.SystemConstants;
import com.ybxx.system.model.User;

public class RecordsAction extends BaseAction {
	@Resource
	private RoomInfoService roomInfoService;
	@Resource
	private RoomService roomService;
	@Resource
	private RecordsService recordsService;
	@Resource
	private ResidentsService residentsService;
	@Resource
	private AnmeterRecordsService anmeterRecordsService;
	@Resource
	private WatermeterRecordsService watermeterRecordsService;
	@Resource
	private WsfRecordService wsfRecordService;
	@Resource
	private HydropowerItemService hydropowerItemService;
	@Resource
	private CommunityService communityService;
	private String unitid;
	private String urlSign;
	private String ymonth;
	private Records records;
	private RecordsVO recordsVO;
	private RoomInfo roomInfo;
	private Room room;
	private List<Room> rooms;
	private List<Records> recodesex;
	private List<RecordsVO> recordsVOs;
	private String msg="succ";
	private String sign;
	public String printNotice(){
		User user=(User)super.getSession().getAttribute(SystemConstants.SESSION_CURRENT_USER);
		/**查询该单元下的所有房屋对应的房屋编号*/
		rooms=roomService.queryRoomRid(unitid,ymonth,user.getLoginid());
		recordsVOs=new ArrayList<RecordsVO>();
		for(Room room:rooms){
			unitid=room.getRid();
			/*1、通过房屋编号，记账月份查询对应的缴费数据*/
			records=recordsService.queryFees(unitid, ymonth);
			/*通过房屋编号查询房屋相关信息*/
			Object[] objs=roomInfoService.load(unitid);
			roomInfo=(RoomInfo)objs[0];
			room=(Room)objs[1];
			Residents residents=null;
			if(records==null){
				residents=residentsService.queryCurrentResidents(unitid);
				if(roomInfo!=null && residents!=null){
					records=generatorFees(roomInfo,room,residents,ymonth);
					/*查询上期缴费记录*/
					Records tmp=recordsService.queryPrevFees(unitid,DateUtil.addMonthFormDate(ymonth+"-01",-1));
					if(tmp==null){
						records.setWarrearage("0");
					}else{
						records.setWarrearage((tmp.getBarrearage()==null || "".equals(tmp.getBarrearage()))?"0":tmp.getBarrearage());
					}
					records.setShouldpay((Float.parseFloat(StringUtils.isEmpty(records.getBfees())?"0":records.getBfees())+Float.parseFloat(StringUtils.isEmpty(records.getWarrearage())?"0":records.getWarrearage()))+"");
					//recordsService.save(records);
				}
			}else{
				residents=records.getResidents();
			}
			/*复制数据到RecordsVO对象中*/
			if(records!=null){
				recordsVO=ConvertRecord.convert(records,roomInfo,room,residents,user);
				recordsVOs.add(recordsVO);
			}
		}
		return "printNotice";
	}
	public String queryPage(){
		QueryFilter filter=new QueryFilter(getRequest());
//		/**获取当前登录者*/
//		User user=(User)super.getSession().getAttribute(SystemConstants.SESSION_CURRENT_USER);
		recodesex=recordsService.queryFeesPage(filter,ymonth,unitid);
		super.setRownum(filter.getPagingBean().getTotalItems());
		super.setCurrentpage(Integer.parseInt(filter.getPagingBean().getStart()+"")/Integer.parseInt(filter.getPagingBean().getPageSize()+"")+1);
		super.setPageSize(Integer.parseInt(filter.getPagingBean().getPageSize()+""));
		return "queryPage";
	}
	public String printFees(){
		/*1、通过房屋编号，记账月份查询对应的缴费数据*/
		records=recordsService.queryFees(unitid, ymonth);
		/*通过房屋编号查询房屋相关信息*/
		Object[] objs=roomInfoService.load(unitid);
		roomInfo=(RoomInfo)objs[0];
		room=(Room)objs[1];
		Residents residents=residentsService.queryCurrentResidents(unitid);
		User user=(User)super.getSession().getAttribute(SystemConstants.SESSION_CURRENT_USER);
		/*复制数据到RecordsVO对象中*/
		recordsVO=ConvertRecord.convert(records,roomInfo,room,residents,user);
		return "printFees";
	}
	public String confirm(){
		try{
			if(Float.parseFloat(records.getCharge())<0){
				records.setBarrearage(records.getCharge());
				records.setCharge("0");
			}else{
				records.setBarrearage("0");
			}
			recordsService.confirm(records);
		}catch(Exception ex){
			msg="确认收费操作失败.";
		}finally{
			return "succ";
		}
	}
	public String save(){
		try{
			if(records.getAnmeterRecord()!=null && StringUtils.isNotEmpty(records.getAnmeterRecord().getAmfcode())){
				records.getAnmeterRecord().setRecords(records);
				if(records.getAnmeterRecord().getItems().size()>0){
					for(AnmeterRecordItem item:records.getAnmeterRecord().getItems()){
						item.setAnmeterRecords(records.getAnmeterRecord());
					}
				}
			}
			if(records.getWatermeterRecord()!=null && StringUtils.isNotEmpty(records.getWatermeterRecord().getWmfcode())){
				records.getWatermeterRecord().setRecords(records);
				if(records.getWatermeterRecord().getItems().size()>0){
					for(WatermeterRecordItem item:records.getWatermeterRecord().getItems()){
						item.setWatermeterRecords(records.getWatermeterRecord());
					}
				}
			}
			if(records.getGlfRecord()!=null  && StringUtils.isNotEmpty(records.getGlfRecord().getGlfrcode())){
				records.getGlfRecord().setRecords(records);
			}
			if(records.getFfRecord()!=null  && StringUtils.isNotEmpty(records.getFfRecord().getFfrcode())){
				records.getFfRecord().setRecords(records);
			}
			if(records.getHlfRecord()!=null  && StringUtils.isNotEmpty(records.getHlfRecord().getHlfrcode())){
				records.getHlfRecord().setRecords(records);
			}
			if(records.getNqfRecord()!=null){
				if(StringUtils.isEmpty(records.getNqfRecord().getNqfrcode())){
					records.getNqfRecord().setNqfrcode(UUIDGenerator.getUUID());
				}
				records.getNqfRecord().setRecords(records);
			}
			if(records.getOtherRecord()!=null){
				if(StringUtils.isEmpty(records.getOtherRecord().getOrcode())){
					records.getOtherRecord().setOrcode(UUIDGenerator.getUUID());
				}
				records.getOtherRecord().setRecords(records);
				if(records.getOtherRecord().getItems().size()>0){
					for(OtherRecordItem item:records.getOtherRecord().getItems()){
						if(StringUtils.isEmpty(item.getRicode())){
							item.setRicode(UUIDGenerator.getUUID());
						}
						item.setOtherRecord(records.getOtherRecord());
					}
				}
			}
			if(records.getWsfRecord()!=null){
				if(StringUtils.isEmpty(records.getWsfRecord().getWsfrcode())){
					records.getWsfRecord().setWsfrcode(UUIDGenerator.getUUID());
				}
				records.getWsfRecord().setRecords(records);
				if(records.getWsfRecord().getItems().size()>0){
					for(WsfRecordItem item:records.getWsfRecord().getItems()){
						if(StringUtils.isEmpty(item.getWicode())){
							item.setWicode(UUIDGenerator.getUUID());
						}
						item.setWsfRecord(records.getWsfRecord());
					}
				}
			}
			recordsService.saveEdit(records);
		}catch(Exception ex){
			ex.printStackTrace();
			msg="收费信息维护失败.";
		}finally{
			return "succ";
		}
	}
	public String checkFees(){
		/*通过房屋编号查询房屋相关信息*/
		Object[] objs=roomInfoService.load(unitid);
		roomInfo=(RoomInfo)objs[0];
		room=(Room)objs[1];
		Residents residents=residentsService.queryCurrentResidents(unitid);
		if(roomInfo==null){
			msg="该房屋编号的房屋信息为空，无法生成费用数据，请维护房屋信息后重试.";
		}
		if(residents==null){
			msg="该房屋暂无住户信息，无法生成费用数据，请维护住户信息后重试.";
		}
		/*检查管理费*/
		int rows=communityService.checkConfig(unitid);
		if(rows>0){
			msg="该小区配置管理费，请在“管理费”功能下配置相应的管理费.";
		}
		return "succ";
	}
	public String checkConfig(){
		msg="succ";
		if(sign==null || sign.equals("")){
			/*查询水电指标配置*/
			int rows=hydropowerItemService.checkConfig(unitid, "001");
			if(rows<=0){
				msg="该小区未配置用水收费指标，请在“水电费”功能下配置相应的用水收费指标.";
				return "succ";
			}
			rows=hydropowerItemService.checkConfig(unitid, "002");
			if(rows<=0){
				msg="该小区未配置用电收费指标，请在“水电费”功能下配置相应的用电收费指标.";
				return "succ";
			}
			/*检查管理费*/
			rows=communityService.checkConfig(unitid);
			if(rows>0){
				msg="该小区配置管理费，请在“管理费”功能下配置相应的管理费.";
				return "succ";
			}
			/*检查房间信息*/
			rows=roomInfoService.checkConfig(unitid);
			if(rows>0){
				msg="0-有些房间没有房间信息，没有房间信息的房间将不能生成收费数据，是否继续";
				return "succ";
			}
		}
		if(sign==null || sign.equals("") || sign.equals("1")){
			/*检查住户信息*/
			int rows=residentsService.checkConfig(unitid);
			if(rows>0){
				msg="1-有些房间没有住户信息，没有住户信息的房间将不能生成收费数据，是否继续";
				return "succ";
			}
		}

		return "succ";
	}
	/*依据房号，记账月份查找对应的缴费记录*/
	public String queryFees(){
		/*1、通过房屋编号，记账月份查询对应的缴费数据*/
		records=recordsService.queryFees(unitid, ymonth);
		/*通过房屋编号查询房屋相关信息*/
		Object[] objs=roomInfoService.load(unitid);
		roomInfo=(RoomInfo)objs[0];
		room=(Room)objs[1];
		
		if(records==null){
			Residents residents=residentsService.queryCurrentResidents(unitid);
			records=generatorFees(roomInfo,room,residents,ymonth);
			/*查询上期缴费记录*/
			Records tmp=recordsService.queryPrevFees(unitid,DateUtil.addMonthFormDate(ymonth+"-01",-1));
			if(tmp==null){
				records.setWarrearage("0");
			}else{
				records.setWarrearage((tmp.getBarrearage()==null || "".equals(tmp.getBarrearage()))?"0":tmp.getBarrearage());
			}
			records.setShouldpay((Float.parseFloat(StringUtils.isNotEmpty(records.getBfees())?records.getBfees():"0.00")+Float.parseFloat(records.getWarrearage()))+"");
			//recordsService.save(records);
		}
		return "queryFees";
	}
    private Records generatorFees(RoomInfo roomInfo,Room room,Residents residents,String ymonth){
    	Records records=new Records();
    	try{
	    	records.setFrcode(UUIDGenerator.getUUID());
			/*计算电表*/
	    	generatorAnmeter(records,roomInfo,room,residents,ymonth);
	    	/*计算水费*/
	    	generatorWatermeter(records,roomInfo,room,residents,ymonth);
	    	/*计算卫生费*/
	    	generatorWsf(records,roomInfo,room,residents,ymonth);
	    	/*计算护楼费*/
	    	generatorHlf(records,roomInfo,room,residents,ymonth);
	    	/*计算管理费*/
	    	generatorGlf(records,roomInfo,room,residents,ymonth);
	    	/*计算房费*/
	    	generatorFf(records,roomInfo,room,residents,ymonth);
	    	/**添加缴费的辅助信息*/
	    	records.setRoom(room);
	    	records.setResidents(residents);
	    	records.setYmonth(ymonth);
    	}catch(Exception ex){
    		ex.printStackTrace();
    	}finally{
    		return records;
    	}
	}
    private void generatorFf(Records records, RoomInfo roomInfo, Room room,
			Residents resident, String ymonth) {
		FfRecord ffRecord=new FfRecord();
		ffRecord.setArea(roomInfo.getCoveredarea());
		ffRecord.setPrice(StringUtils.isEmpty(room.getUnit().getBan().getCommunity().getRprice())?"0":room.getUnit().getBan().getCommunity().getRprice());
		ffRecord.setCurrentcost((Float.parseFloat(ffRecord.getArea())*Float.parseFloat(ffRecord.getPrice()))+"");
		ffRecord.setFfrcode(UUIDGenerator.getUUID());
		ffRecord.setSetupcost("0");
		ffRecord.setCombined(ffRecord.getCurrentcost());
		records.getFfRecords().add(ffRecord);
		records.setBfees((Float.parseFloat(records.getBfees())+Float.parseFloat(ffRecord.getCombined()))+"");
		
	}
	private void generatorGlf(Records records, RoomInfo roomInfo, Room room,
			Residents residents, String ymonth) {
    	GlfRecord glfRecord=new GlfRecord();
    	glfRecord.setGlfrcode(UUIDGenerator.getUUID());
    	glfRecord.setRecords(records);
    	glfRecord.setPrice(room.getUnit().getBan().getCommunity().getGlprice());
		if(room.getUnit().getBan().getCommunity().getGlrule()==null || room.getUnit().getBan().getCommunity().getGlrule().getCrid().equals("001")){//按面积计算
			glfRecord.setRnum(roomInfo.getCoveredarea());
		}else if(room.getUnit().getBan().getCommunity().getGlrule().getCrid().equals("002")){//按户数计算
			glfRecord.setRnum("1");
		}
		glfRecord.setBsum((Float.parseFloat(glfRecord.getRnum())*Float.parseFloat(glfRecord.getPrice()))+"");
		glfRecord.setTfees("0");
		glfRecord.setLatefees(glfRecord.getBsum());
		records.getGlfRecords().add(glfRecord);
		records.setBfees((Float.parseFloat(records.getBfees())+Float.parseFloat(glfRecord.getBsum()))+"");
		
	}
	private void generatorAnmeter(Records records,RoomInfo roomInfo,Room room,Residents residents,String ymonth){
    	/*查询住户电表指标*/
    	AnmeterRecords anmeterRecords=anmeterRecordsService.generator(room, residents, ymonth);
    	if(anmeterRecords!=null){
	    	anmeterRecords.setRecords(records);
	    	records.getAnmeterRecords().add(anmeterRecords);
	    	records.setBfees(anmeterRecords.getReceivable());
    	}
    }
    private void generatorWatermeter(Records records,RoomInfo roomInfo,Room room,Residents residents,String ymonth){
    	/*查询住户水表指标*/
    	WatermeterRecords watermeterRecords=watermeterRecordsService.generator(room, residents, ymonth);
    	if(watermeterRecords!=null){
	    	watermeterRecords.setRecords(records);
	    	records.getWatermeterRecords().add(watermeterRecords);
	    	records.setBfees((Float.parseFloat(records.getBfees())+Float.parseFloat(watermeterRecords.getReceivable()))+"");
    	}
    }
    private void generatorWsf(Records records,RoomInfo roomInfo,Room room,Residents residents,String ymonth){
    	/*查询住户卫生费*/
    	WsfRecord wsfRecord=wsfRecordService.generator(room, residents, ymonth);
    	if(wsfRecord!=null){
	    	wsfRecord.setRecords(records);
	    	records.getWsfRecords().add(wsfRecord);
	    	records.setBfees((Float.parseFloat(records.getBfees())+Float.parseFloat(wsfRecord.getReceivable()))+"");
    	}
    }
    private void generatorHlf(Records records,RoomInfo roomInfo,Room room,Residents residents,String ymonth){
    	/*查询住户护楼费*/
    	HlfRecord hlfRecord=new HlfRecord();
    	hlfRecord.setHlfrcode(UUIDGenerator.getUUID());
    	hlfRecord.setRecords(records);
    	hlfRecord.setCombined(StringUtils.isEmpty(room.getUnit().getBan().getCommunity().getBuildingcharge())?"0":room.getUnit().getBan().getCommunity().getBuildingcharge());
    	hlfRecord.setFees("0");
    	hlfRecord.setRealfees(hlfRecord.getCombined());
    	records.getHlfRecords().add(hlfRecord);
    	records.setBfees((Float.parseFloat(records.getBfees())+Float.parseFloat(hlfRecord.getCombined()))+"");
    }
	public String getUnitid() {
		return unitid;
	}
	public void setUnitid(String unitid) {
		this.unitid = unitid;
	}
	public String getUrlSign() {
		return urlSign;
	}
	public void setUrlSign(String urlSign) {
		this.urlSign = urlSign;
	}
	public String getYmonth() {
		return ymonth;
	}
	public void setYmonth(String ymonth) {
		this.ymonth = ymonth;
	}
	public Records getRecords() {
		return records;
	}
	public void setRecords(Records records) {
		this.records = records;
	}
	public RoomInfo getRoomInfo() {
		return roomInfo;
	}
	public void setRoomInfo(RoomInfo roomInfo) {
		this.roomInfo = roomInfo;
	}
	public Room getRoom() {
		return room;
	}
	public void setRoom(Room room) {
		this.room = room;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public RecordsVO getRecordsVO() {
		return recordsVO;
	}
	public void setRecordsVO(RecordsVO recordsVO) {
		this.recordsVO = recordsVO;
	}
	public List<Records> getRecodesex() {
		return recodesex;
	}
	public void setRecodesex(List<Records> recodesex) {
		this.recodesex = recodesex;
	}
	public List<Room> getRooms() {
		return rooms;
	}
	public void setRooms(List<Room> rooms) {
		this.rooms = rooms;
	}
	public List<RecordsVO> getRecordsVOs() {
		return recordsVOs;
	}
	public void setRecordsVOs(List<RecordsVO> recordsVOs) {
		this.recordsVOs = recordsVOs;
	}
	public String getSign() {
		return sign;
	}
	public void setSign(String sign) {
		this.sign = sign;
	}
	
}
